/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.redis.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.iwindplus.boot.domain.constant.CommonConstant.SymbolConstant;
import com.iwindplus.boot.redis.domain.annotation.RedisRateLimiter;
import com.iwindplus.boot.redis.service.RateLimiterKeyResolver;
import com.iwindplus.boot.util.ExpressionUtil;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.cache.interceptor.KeyGenerator;

/**
 * 限流Key解析器接口实现类（默认（全局级别）限流Key解析器）.
 *
 * @author zengdegui
 * @since 2020/6/13
 */
public class DefaultRateLimiterKeyResolver implements RateLimiterKeyResolver {

    @Override
    public String resolver(JoinPoint joinPoint, KeyGenerator keyGenerator, RedisRateLimiter rateLimiter) {
        Object target = joinPoint.getTarget();
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Object[] args = joinPoint.getArgs();
        String[] keys = rateLimiter.keys();
        if (ArrayUtil.isNotEmpty(args) && ArrayUtil.isNotEmpty(keys)) {
            final List<Object> resultList = ExpressionUtil.parse(method, joinPoint.getArgs(), keys, Object.class);
            if (CollUtil.isNotEmpty(resultList)) {
                return resultList.stream().map(Object::toString).collect(Collectors.joining(SymbolConstant.UNDERLINE));
            }
        }
        return keyGenerator.generate(target, method, args).toString();
    }
}
